package com.jn.erp.web.api.course.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jn.erp.utils.DateUtils;
import com.jn.erp.utils.RedisLock;
import com.jn.erp.web.api.course.entity.TCourseOrder;
import com.jn.erp.web.api.course.entity.TCourseOrderConfig;
import com.jn.erp.web.api.course.mapper.TCourseOrderConfigMapper;
import com.jn.erp.web.api.course.service.TCourseOrderService;
import com.jn.erp.web.api.student.entity.StudentCourse;
import com.jn.erp.web.api.student.entity.TStudentClassRela;
import com.jn.erp.web.api.student.entity.TStudentCourse;
import com.jn.erp.web.api.student.mapper.StudentCourseMapper;
import com.jn.erp.web.api.student.mapper.TStudentClassRelaMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 周期性对已过期订单进行清空处理
 * */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class StudentCourseTask {

    @Autowired
    private RedisLock redisLock;

    @Autowired
    private StudentCourseMapper studentCourseMapper;
    //每天1:00运行
    @Scheduled(cron = "0 0 1 * * ?")
    public void checkExpireDate() {
        log.info("----------------------------  StudentCourseTask   start --------------------------------------");
        Boolean idxScoreReportsTask = redisLock.lock("StudentCourseTask:checkExpireDate");
        if(!idxScoreReportsTask){
            return;
        }

        try {
            List<StudentCourse> studentCourses = studentCourseMapper.selectList(new QueryWrapper<StudentCourse>().eq("deleted", 0).eq("exhausted", 1).lt("DATE_FORMAT( expire_date, '%Y-%m-%d' )", DateUtils.getCurrentDate1()));
            if (!CollectionUtils.isEmpty(studentCourses)){
                studentCourses.stream().forEach(u->{
                    u.setExhausted(0);
                    u.setExhaustedType(4);
                    u.setEditTime(LocalDateTime.now());
                    u.setEditor(-1L);
                    studentCourseMapper.updateById(u);
                });
            }

            log.info("---------------------------- Create StudentCourseTask   end --------------------------------------");
        } catch (Exception e) {
            System.out.println("StudentCourseTask=====>>>>>"+e.getMessage());
            log.info(e.getMessage());
            e.printStackTrace();
        }finally {
            redisLock.del("StudentCourseTask:checkExpireDate");
        }

    }
}
